import { Component, Node } from "cc";
import { IGameComponent, IGameEntity } from "./interface/ecsEnterface";

export class GameEntity extends Component implements IGameEntity{
    params:any;
    protected __preload(): void {
        this.init();
    }
    

    protected init(){
        //子类实现
    } 
    
    private _list:IGameComponent[]=[]
    add<T extends IGameComponent>(comp: new () => T) {
        let component:IGameComponent=new comp();
        component["_owner"]=this
        component["_node"]=this.node
        component["init"] && component["init"]();
        this._list.push(component)
    }
    get(name: string): IGameComponent {
        for(let i=0;i<this._list.length;i++){
            if(this._list[i].NAME == name){
                return this._list[i]
            }
        }
        return null
    }
    remove(name: string) {
        for(let i=0;i<this._list?.length;i++){
            if(this._list[i].NAME == name){
                this._list[i].remove(this._list[i].NAME)
                this._list[i]=null
                this._list.splice(i,1)
                break
            }
        }
    }
    removeAll(){
        for(let i=0;i<this._list?.length;i++){
            this._list[i].removeAll();
            this._list[i]=null;
            this._list.splice(i,1)
            i--
        } 
    }
    update(dt:number){
        if(this._list){
            for(let i=0;i<this._list.length;i++)this._list[i] && this._list[i].update(dt)
        }
        
    }
    lateUpdate(dt: number) {
        if(this._list){
            for(let i=0;i<this._list.length;i++)this._list[i] && this._list[i].lateUpdate(dt)
        }
    }
    
}